package com.Xht.www.servlet;

//后端响应查看拉黑商家的请求
import com.Xht.www.dao.UserBlacklistDAO;
import com.Xht.www.po.UserBlacklistPO;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/check-blacklist")
public class CheckBlacklistServlet extends HttpServlet {
    private UserBlacklistDAO blacklistDAO = new UserBlacklistDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            // 获取参数
            Integer userId = Integer.parseInt(req.getParameter("userId"));
            String merchantName = req.getParameter("merchantName");

            // 验证参数
            if (userId == null || merchantName == null) {
                resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                resp.getWriter().write("false");
                return;
            }

            // 检查商家是否已经被该用户拉黑
            boolean isBlacklisted = checkIfMerchantBlacklisted(userId, merchantName);

            // 返回结果
            resp.setContentType("application/json");
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().write(String.valueOf(isBlacklisted));
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("false");
        }
    }

    // 检查商家是否已经被该用户拉黑
    private boolean checkIfMerchantBlacklisted(int userId, String merchantName) {
        List<UserBlacklistPO> blacklists = blacklistDAO.getUserBlacklistsByUserId(userId);
        for (UserBlacklistPO blacklist : blacklists) {
            if (blacklist.getMerchantName().equals(merchantName)) {
                return true;
            }
        }
        return false;
    }
}
